<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    JS RegExp.md |  Small Bridge
  </title>
  <meta name="generator" content="hexo-theme-yilia-plus">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/css/main.css">

  
  <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
  
  

  

<link rel="alternate" href="/atom.xml" title="Small Bridge" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    <main class="content">
      <section class="outer">
  <article id="post-JS-RegExp-md" class="article article-type-post" itemscope
  itemprop="blogPost" data-scroll-reveal>

  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  JS RegExp.md
</h1>
  

    </header>
    

    
    <div class="article-meta">
      <a href="/2020/04/12/JS-RegExp-md/" class="article-date">
  <time datetime="2020-04-12T09:33:01.000Z" itemprop="datePublished">2020-04-12</time>
</a>
      
  <div class="article-category">
    <a class="article-category-link" href="/categories/JavaScript/">JavaScript</a>
  </div>

      
      
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">5.6k字</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">23分钟</span>
        </span>
    </span>
</div>

      
    </div>
    

    
    
    <div class="tocbot"></div>





    

    
    <div class="article-entry" itemprop="articleBody">
      


      

      
      <p>@<a href="JS正则表达式">TOC</a></p>
<a id="more"></a>
<h1 id="什么是正则"><a href="#什么是正则" class="headerlink" title="什么是正则"></a>什么是正则</h1><p>概念:<br>正则表达式是对字符串（包括普通字符（例如，a 到 z 之间的字母）和特殊字符（称为“元字符”））操作的一种逻辑公式，就是用事先定义好的一些特定字符、及这些特定字符的组合，组成一个“规则字符串”，这个“规则字符串”用来表达对字符串的一种过滤逻辑。正则表达式是一种文本模式，该模式描述在搜索文本时要匹配的一个或多个字符串。<br>语法:<br>/正则表达式内容/模式修正符(可有可无),由两个斜线包裹起来的检索匹配模式。</p>
<h1 id="使用正则的优势"><a href="#使用正则的优势" class="headerlink" title="使用正则的优势"></a>使用正则的优势</h1><p>我们在了解了正则的概念之后，通过一个例子来看一下使用正则的优势:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1.使用正则表达式的优势</span></span><br><span class="line">  <span class="comment">//问题描述，找出一串字符中的数字</span></span><br><span class="line">  <span class="keyword">let</span> hd = <span class="string">"sdsxcakdkl123sdshdk456"</span>;</span><br><span class="line">  <span class="comment">//不使用正则表达式</span></span><br><span class="line">  <span class="keyword">let</span> nums =  [...hd].filter(<span class="function"><span class="params">search</span> =&gt;</span> !<span class="built_in">Number</span>.isNaN(<span class="built_in">parseInt</span>(search)));</span><br><span class="line">  <span class="built_in">console</span>.log(nums.join(<span class="string">""</span>));</span><br><span class="line">  <span class="comment">//使用正则表达式</span></span><br><span class="line">  <span class="built_in">console</span>.log(hd.match(<span class="regexp">/\d/g</span>).join(<span class="string">""</span>));</span><br></pre></td></tr></table></figure>
<p>不使用正则表示式的情况，看似只有一句代码，实际上它做了很多工作，将hd字符串展开并变为数组，再使用数组的过滤方法对每一个字符进行转换成int的操作并加以判断，最后将过滤好的数组用join方法连接成一个字符串，反观我们的正则表达式，强大。</p>
<h1 id="创建正则表达式的方法"><a href="#创建正则表达式的方法" class="headerlink" title="创建正则表达式的方法"></a>创建正则表达式的方法</h1><p>创建正则表达式一般有两种方法:<br>1.字面量创建正则表达式<br>2.使用对象创建正则表达式<br>不多说，我们看代码:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//字面量创建方式</span></span><br><span class="line">  <span class="keyword">let</span> kk = <span class="string">"https://lockme.gitee.io"</span>;</span><br><span class="line">  <span class="keyword">let</span> a = <span class="string">"m"</span>;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="regexp">/m/</span>.test(kk));</span><br><span class="line">  <span class="comment">//字面量形式不能直接使用变量a，但是可以间接使用如下,eval里面为字符串模板的符号(esc键下面的键)</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="built_in">eval</span>(<span class="string">`/<span class="subst">$&#123;a&#125;</span>/`</span>).test(kk));</span><br><span class="line">  <span class="comment">//使用对象创建正则表达式,后面的g是模式修正符，后面会讲到</span></span><br><span class="line">  <span class="keyword">let</span> reg = <span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">'m'</span>,<span class="string">'g'</span>); <span class="comment">//可以直接使用变量  等同于reg = new RegExp(a,"g")</span></span><br><span class="line">  <span class="built_in">console</span>.log(reg.test(kk));</span><br></pre></td></tr></table></figure>
<h1 id="介绍一些正则中常用的方法"><a href="#介绍一些正则中常用的方法" class="headerlink" title="介绍一些正则中常用的方法"></a>介绍一些正则中常用的方法</h1><p>正则中常使用的方法有：<br>1.正则表达式的方法(由正则表达式使用)test和exec</p>
<p>1.1 正则表达式.test(string),表示使用前面的正则表达式检索参数中传入的字符串,匹配成功返回true，<br>匹配失败返回false。<br>1.2 正则表达式.exec(string),表示使用前面的正则表达式检索参数中传入的字符串，但是匹配成功返回的是匹配的值，单次匹配与test方法差不多，但是多次匹配的话，它会记录一个lastIndex(后面会讲)的值，下次匹配从lastIndex的下一位置继续匹配。</p>
<p>2.字符串的方法search、match、matchAll、split、replace</p>
<p>2.1 字符串.search(string | RegExp),表示搜素指定字符串，返回索引，失败则返回-1，支持传入正则表达式作为参数。<br>2.2 字符串.match(string | RegExp),搜索指定字符串，返回一个数组，里面装的所有匹配的值，支持传入正则表达式作为参数。<br>2.3 字符串.matchAll(string | RegExp),全局匹配， 方法返回一个包含所有匹配正则表达式的结果及分组捕获组的迭代器。<br>2.4 字符串.split(string),拆分，以传入的参数字符串拆分，返回拆分后元素的数组，支持传入正则,返回拆分成的数组。<br>2.4 字符串.replace(string | RegExp,”xxx” | function),将指定的字符串替换，可以传入替换的字符串或者是实现替换的回调函数，返回替换后的字符串。</p>
<h1 id="选择符的使用"><a href="#选择符的使用" class="headerlink" title="选择符的使用"></a>选择符的使用</h1><p>选择符 | 表示or的关系，/表达式1 | 表达式2/  表示只匹配其中的一个即可</p>
<h1 id="元字符的使用"><a href="#元字符的使用" class="headerlink" title="元字符的使用"></a>元字符的使用</h1><p>只列举一些常用的，完整的可以自行百度查看。<br>元字符 | 内容<br>— | —<br>\d | 匹配数字字符<br>\D| 匹配除了数字的字符<br>\s | 匹配空白字符(回车、空格、制表符等)<br>\S | 匹配除了空白字符的字符<br>\w | 匹配字母、数字、下划线<br>\W | 匹配除了字母、数字、下划线的字符<br>.   | 除了换行符\n的所有字符<br>^ | 表示以什么字符开始<br>$ | 表示以什么字符结束</p>
<h1 id="量词的使用"><a href="#量词的使用" class="headerlink" title="量词的使用"></a>量词的使用</h1><p>同样只列举一些<br>量词 | 内容<br>— | —<br>{n} | 表示出现的字符串的长度为n<br>{m,n}| 表示出现的字符串的长度为m~n之间<br>{m,} | 至少m个<br>? | {0,1}，0个或者1个</p>
<ul>
<li>| {0,}，0个或者多个</li>
</ul>
<ul>
<li>| {1,}，1个或者多个<br>关于量词还多其他知识，比如量词的分类，贪婪量词，惰性量词和支配性量词，想了解可自行百度。<h1 id="重复匹配"><a href="#重复匹配" class="headerlink" title="重复匹配"></a>重复匹配</h1>元字符后面跟量词达到重复匹配的效果，比如：<br>/d+  表示匹配一个或者多个数字<br>/w* 表示匹配0个或者多个字母数字下划线<br>/s? 表示匹配0个或者一个空白字符<br>[123]{2,3} 表示匹配2到3个’1’、’2’、’3’字符中的其中一个<br>(123){5} 表示匹配5个’123’串<br>最后两个是下面要讲的原子表和原子组<h1 id="原子表和原子组"><a href="#原子表和原子组" class="headerlink" title="原子表和原子组"></a>原子表和原子组</h1></li>
</ul>
<p>1.原子表<br>用中括号包括起来的，表示或的关系，只匹配其中的一个字符。<br>举例:[1234] 表示匹配1，2，3，4四个字符中的一个字符，相当于1 | 2 | 3 | 4。</p>
<p>1.1 区间匹配<br>[a-z]表示所有26个小写字母字符。<br>[0-9]表示所有数字字符。<br>[A-Z]表示所有大写字母字符。</p>
<p>1.2 排除匹配<br>[^ue]表示除了ue两个字符均匹配。</p>
<p>1.3 原子表字符不解析<br>() 和.+ 放入原子表中不会有正则表达式的含义，只保留字符串的本义。<br>[()]表示匹配括号。<br>[.+]表示匹配字符’.’或者’+’</p>
<p>1.4使用原子表匹配任意内容<br>尽管有元字符.,但也不能匹配任意字符，因为它是除了换行符，那么如何匹配任意内容？我们通常使用<br>[\s\S],意思是匹配空白字符或者除了空白字符的其他字符，就是任意字符，同样也可以使用[\d\D]等。</p>
<p>2.原子组<br>用括号包括起来的，表示一个整体，匹配相同整体的内容。<br>举例:(1234),表示匹配’1234’这样一个整体的字符串</p>
<p>2.1邮箱验证中原子组的使用</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;input type=<span class="string">"text"</span> name=<span class="string">"email"</span>&gt;</span><br><span class="line">    &lt;span&gt;&lt;<span class="regexp">/span&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="built_in">document</span>.querySelector(<span class="string">`[name="email"]`</span>).addEventListener(<span class="string">'keyup'</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">       <span class="comment">//一些邮箱的格式 10807396@qq.com  100@sina.com.cn</span></span><br><span class="line">       <span class="keyword">let</span> reg = <span class="regexp">/^[\w-]+@([\w-]+\.)+(com|org|cn|net|cc)$/i</span>;</span><br><span class="line">       <span class="built_in">document</span>.querySelector(<span class="string">`span`</span>).innerHTML = reg.test(<span class="keyword">this</span>.value)?<span class="string">"正确"</span>:<span class="string">"错误"</span>;</span><br><span class="line">    &#125;);</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<p>算是文章的真正意义上的第一个正则的例子，我细讲一下表达式的匹配吧，后面的例子就不赘述了，得你自己去看。一般邮箱这样的字符串都得严格规定开始和结束的字符，所以使用^和$，第一个原子组中表示匹配字母数字下划线和-,后跟量词+(这个+是量词，千万不要看成其它意义上的加号了)表示匹配一个或者多个，第一部分^[\w-]+就表示匹配一个或者多个字母、数字、下划线和-并以其开头,@符就是表示匹配@符，下一个[\w+.]表示匹配一个或者多个字母数字下划线和点，因为点在正则中是有含义的，所以使用反斜杠进行转义，用原子组包起来是因为像这样模式的字符串可能不止一组，像<a href="mailto:100@sina.com.cn">100@sina.com.cn</a>这样的就有两组sina.和com.，所以包括起来使用量词一个或者多个，最后匹配以com、org、cn、net、cc结尾的其中一个字符，i表示不区分大小写，是下面要讲的模式修正符。</p>
<p>2.2 原子组引用完成替换操作</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="keyword">let</span> hd = <span class="string">`</span></span><br><span class="line"><span class="string">        &lt;h1&gt;smallbridge&lt;/h1&gt;</span></span><br><span class="line"><span class="string">        &lt;span&gt;前端者&lt;/span&gt;</span></span><br><span class="line"><span class="string">        &lt;h2&gt;lockme&lt;/h2&gt;</span></span><br><span class="line"><span class="string">    `</span>;</span><br><span class="line">    <span class="comment">//将h标签变成p标签</span></span><br><span class="line">    <span class="keyword">let</span> reg = <span class="regexp">/&lt;(h[1-6])&gt;([\s\S]*)&lt;\/\1&gt;/gi</span>;</span><br><span class="line">    <span class="comment">//$2表示取第二个原子组中的内容</span></span><br><span class="line">    <span class="comment">//console.log(hd.replace(reg,`&lt;p&gt;$2&lt;/p&gt;`));</span></span><br><span class="line">    <span class="comment">//也可以使用函数的方式,其中传入的参数，p0表示匹配的所有字符串，</span></span><br><span class="line">    <span class="comment">//p1表示第一个原子组，p2表示第二个原子组，依次类推</span></span><br><span class="line">    <span class="keyword">let</span> res = hd.replace(reg,(p0,p1,p2)=&gt;<span class="string">`&lt;p&gt;<span class="subst">$&#123;p2&#125;</span>&lt;/p&gt;`</span>);</span><br><span class="line">    <span class="comment">// hd.replace(reg,(p0,p1,p2) =&gt;&#123;</span></span><br><span class="line">    <span class="comment">//     console.log(p0);</span></span><br><span class="line">    <span class="comment">// &#125;);</span></span><br><span class="line">    <span class="built_in">console</span>.log(res);</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<p>首先提一下正则中的\1,它表示这里匹配的模式与前面第一个原子组中的模式相同,前面匹配好h1后面也会跟着匹配h1，这个数字是怎么来的，从左往右数，第一个就是\1,第二个就是\2,有人要问为什么不是从0开始？因为0表示匹配的整个字符串。<br>这个要完成替换就要将标签中的内容提取出来，一般情况下，需要被提取的内容在正则表达式中都使用原子组包起来，然后使用$加序号就可以提取了。<br>嵌套原子组的序号怎么看？从左往右，从外往里</p>
<p>2.3 不记录组<br>有时候会出现一个正则表达式中原子组很多的情况，那么其的序号势必会增大，这样会造成不好的后果，不记录组的作用就出来了，将不需要提取值的原子组标记为不记录组。在原子组中使用(?:)表示此组不记录编号，无法使用$编号提取，这样序号就会小很多。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="keyword">let</span> hd = <span class="string">`</span></span><br><span class="line"><span class="string">    https://www.lockme.gitee.io</span></span><br><span class="line"><span class="string">    http://github.com</span></span><br><span class="line"><span class="string">    https://hdcms.com</span></span><br><span class="line"><span class="string">    `</span>;</span><br><span class="line">    <span class="comment">//?表示&#123;0,1&#125;可有可无，s不是必须的，有s没有s均匹配</span></span><br><span class="line">    <span class="keyword">let</span> reg = <span class="regexp">/https?:\/\/(\w+\.)+(com|org|io|cc|cn)/ig</span>;</span><br><span class="line">    <span class="built_in">console</span>.dir(hd.match(reg));</span><br><span class="line">    <span class="comment">//在原子组中使用?:，表示此组不记录编号，无法使用$加编号访问，用于忽略那些不用取值的组</span></span><br><span class="line">    <span class="keyword">let</span> regg = <span class="regexp">/https?:\/\/(?:\w+\.)+(com|org|io|cc|cn)/ig</span>;</span><br><span class="line">    <span class="comment">//第一个原子组忽略记录编号</span></span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<p>2.4 原子组在替换中的使用技巧</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;main&gt;</span><br><span class="line">        &lt;a style=<span class="string">"color:red"</span> href=<span class="string">"http://www.hdcms.com"</span>&gt;</span><br><span class="line">            开源系统</span><br><span class="line">        &lt;<span class="regexp">/a&gt;</span></span><br><span class="line"><span class="regexp">        &lt;a id="l1" href="http:/</span><span class="regexp">/houdunren.com"&gt;后盾人&lt;/</span>a&gt;</span><br><span class="line">        &lt;a href=<span class="string">"http://yahoo.com"</span>&gt;雅虎&lt;<span class="regexp">/a&gt;</span></span><br><span class="line"><span class="regexp">        &lt;h4&gt;http:/</span><span class="regexp">/www.hdcms.com&lt;/</span>h4&gt;</span><br><span class="line">    &lt;<span class="regexp">/main&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="comment">//要求 将便签的herf属性中的地址加s和www</span></span><br><span class="line">    <span class="keyword">const</span> main = <span class="built_in">document</span>.querySelector(<span class="string">'body main'</span>);</span><br><span class="line">    <span class="keyword">const</span> reg = <span class="regexp">/(&lt;a.*href=["'])(http)(:\/\/)(www\.)?(hdcms|houdunren)/g</span>;</span><br><span class="line">    <span class="comment">//args是es6的语法，剩余参数，允许我们将不定数量的一个参数表示为一个数组</span></span><br><span class="line">    main.innerHTML = main.innerHTML.replace(reg,(v,...args)=&gt;&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(args);</span><br><span class="line">        args[<span class="number">1</span>] += <span class="string">'s'</span>;</span><br><span class="line">        args[<span class="number">3</span>] = args[<span class="number">3</span>] || <span class="string">'www.'</span>;</span><br><span class="line">        <span class="comment">//修改之后，将修改后的重新连接起来</span></span><br><span class="line">        <span class="keyword">return</span> args.splice(<span class="number">0</span>,<span class="number">5</span>).join(<span class="string">''</span>);</span><br><span class="line">    &#125;)</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<h1 id="模式修正符"><a href="#模式修正符" class="headerlink" title="模式修正符"></a>模式修正符</h1><p>上面已经提到了，在正则表达式的末尾添加模式修正符，常用的有：<br>模式     | 内容<br>——– | —–<br>i  | 不区分大小写<br>g | 全局匹配<br>m | 多行匹配，每一行单独处理<br>u | 宽字节匹配模式<br>s | 单行匹配模式</p>
<p>关于多行匹配，我们看一个例子:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="comment">//多行匹配</span></span><br><span class="line">    <span class="keyword">let</span> hd = <span class="string">`</span></span><br><span class="line"><span class="string">    #1 js,200元 #</span></span><br><span class="line"><span class="string">    #2 php,300元 #</span></span><br><span class="line"><span class="string">    #9 lockme.gitee.io #</span></span><br><span class="line"><span class="string">    #3 node.js,180元 #</span></span><br><span class="line"><span class="string">    `</span>;</span><br><span class="line">    <span class="comment">//将上述字符串输出成[&#123;"name":"js","price":"200元"&#125;]格式</span></span><br><span class="line">    <span class="comment">//m表示多行匹配，就是每一行单独处理，不这样的话，你去写匹配很麻烦的，不信你可以试试</span></span><br><span class="line">    <span class="comment">//我中间写的是 .+ 表示匹配除换行的任意字符，如果不多行匹配的话,以第一个为例</span></span><br><span class="line">    <span class="comment">//.+就会匹配到 js,200元 # ,然后才是最后的若干空白字符#结尾，整个表达式匹配的内容就会变成</span></span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">      </span></span><br><span class="line"><span class="comment">      #1 js,200元 #</span></span><br><span class="line"><span class="comment">      #</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="comment">//显然这样是不行的</span></span><br><span class="line">    <span class="keyword">let</span> lessons = hd.match(<span class="regexp">/^\s*#\d+\s+.+\s+#$/gm</span>).map(<span class="function"><span class="params">v</span>=&gt;</span>&#123;</span><br><span class="line">        <span class="comment">//删除不必要的字符</span></span><br><span class="line">        v = v.replace(<span class="regexp">/\s*#\d+\s*/</span>,<span class="string">""</span>).replace(<span class="regexp">/\s+#/</span>,<span class="string">""</span>);</span><br><span class="line">        <span class="comment">//解构赋值</span></span><br><span class="line">        [name,price] = v.split(<span class="string">","</span>);</span><br><span class="line">        <span class="keyword">return</span> &#123;name,price&#125;;</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="comment">//以JSON格式打印</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">JSON</span>.stringify(lessons,<span class="literal">null</span>,<span class="number">2</span>))</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<h1 id="转义字符"><a href="#转义字符" class="headerlink" title="转义字符"></a>转义字符</h1><p>上面也已经提到，若要在正则表达式中匹配一些拥有正则含义的字符，应当使用反斜杠进行转义。比如点、$、+、*、？等。<br>关于转义需要注意一点:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = <span class="number">12.34</span>;</span><br><span class="line"><span class="built_in">console</span>.log(<span class="regexp">/\d+\.\d+/</span>.test(a));   <span class="comment">//转义.这个符号</span></span><br><span class="line"><span class="comment">//但如果使用字符串形式</span></span><br><span class="line"><span class="keyword">let</span> reggg = <span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">'\d+\.\d+'</span>,<span class="string">'g'</span>);  </span><br><span class="line"><span class="comment">//将会被解析成d+.d+,表示的意思是若干d任意字符若干d,因为在字符串中 \d就等于d \.就等于 .</span></span><br><span class="line"><span class="comment">//你可以试着输出一下 'd' === '\d',看是否为true</span></span><br><span class="line"><span class="comment">//无法匹配</span></span><br><span class="line"><span class="built_in">console</span>.log(reggg.test(a));</span><br><span class="line"><span class="comment">//所以需要再次转义</span></span><br><span class="line"><span class="keyword">let</span> re = <span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">'\\d+\\.\\d+'</span>,<span class="string">'g'</span>);</span><br><span class="line"><span class="built_in">console</span>.log(re.test(a))</span><br></pre></td></tr></table></figure>
<h1 id="汉字与字符属性"><a href="#汉字与字符属性" class="headerlink" title="汉字与字符属性"></a>汉字与字符属性</h1><p>/\p{xxx}/u 这样的正则表达式表示只匹配某类字符，根据字符属性确定，比如：<br>/\p{L}/u 只匹配字母<br>/\p{P}/u 只匹配标点符号<br>/\p{sc=Han}/u 只匹配中文<br>其他的字符属性可查看百度</p>
<h1 id="lastIndex的作用"><a href="#lastIndex的作用" class="headerlink" title="lastIndex的作用"></a>lastIndex的作用</h1><p>正则表达式在不加模式修正符g的情况下是只会匹配一次的，后面再有符合条件的内容也不会再匹配了。<br>在正则表达式的方法中有一个exec()方法，它会记录上一次匹配的位置(lastIndex)，下一次匹配的时候紧接着上一次匹配的位置开始匹配，仅在全局模式下，非全局模式始终匹配第一个。<br>使用exec完成全局匹配:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="comment">//在全局模式下(必要条件)，正则表达式的exec方法会记录上一次匹配的位置(lastIndex)</span></span><br><span class="line">    <span class="keyword">let</span> hd = <span class="string">"lockme.gitee.io"</span>;</span><br><span class="line">    <span class="keyword">let</span> reg = <span class="regexp">/\w/g</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(reg.lastIndex);</span><br><span class="line">    <span class="built_in">console</span>.log(reg.exec(hd));</span><br><span class="line">    <span class="built_in">console</span>.log(reg.lastIndex);</span><br><span class="line">    <span class="built_in">console</span>.log(reg.exec(hd));</span><br><span class="line"></span><br><span class="line">    <span class="comment">// while(res = reg.exec(hd))&#123;</span></span><br><span class="line">    <span class="comment">//     console.log(res);</span></span><br><span class="line">    <span class="comment">// &#125;</span></span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>

<h1 id="批量使用正则匹配同一字符串"><a href="#批量使用正则匹配同一字符串" class="headerlink" title="批量使用正则匹配同一字符串"></a>批量使用正则匹配同一字符串</h1><p>有时候会有非常复杂的字符串，想要写出匹配它的正则表达式十分困难，这时我们就可以将其进行拆分，拆分成满足若干条件的字符串，这样或许就会简单许多。不多说，我们看例子：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;input type=<span class="string">"text"</span> name=<span class="string">"password"</span>&gt;</span><br><span class="line">&lt;<span class="regexp">/body&gt;</span></span><br><span class="line"><span class="regexp">&lt;script&gt;</span></span><br><span class="line"><span class="regexp">    const input = document.querySelector(`[name="password"]`);</span></span><br><span class="line"><span class="regexp">    input.addEventListener("keyup", e=&gt;&#123;</span></span><br><span class="line"><span class="regexp">        const value = e.target.value;</span></span><br><span class="line"><span class="regexp">        /</span><span class="regexp">/批量使用正则表达式</span></span><br><span class="line"><span class="regexp">        const regs = [</span></span><br><span class="line"><span class="regexp">            /^[a-z0-9]&#123;5,9&#125;$/i</span>,</span><br><span class="line">            /[A-Z]/,</span><br><span class="line">            /[<span class="number">0</span><span class="number">-9</span>]/</span><br><span class="line">        ]</span><br><span class="line">        <span class="comment">//使用数组的every方法，里面的每一个均返回true时，结果才为true，否则就为false</span></span><br><span class="line">        <span class="keyword">let</span> state = regs.every(<span class="function"><span class="params">e</span> =&gt;</span> e.test(value));</span><br><span class="line">        <span class="built_in">console</span>.log(state ? <span class="string">"正确"</span> : <span class="string">"错误"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// let regg = /^[0-9a-zA-Z]&#123;5,9&#125;$/;</span></span><br><span class="line">        <span class="comment">// console.log(regg.test(value));</span></span><br><span class="line">    &#125;)</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<h1 id="禁止贪婪"><a href="#禁止贪婪" class="headerlink" title="禁止贪婪"></a>禁止贪婪</h1><p>我们使用的量词通常都是贪婪的，什么是贪婪？比如\d+表示匹配一个或者多个字符，在匹配检索的时候它都会尽可能多的匹配满足条件的字符，这就是贪婪。在有些情况下，我们是需要禁止这种贪婪的，禁止贪婪简单来说就是使量词偏向少的一方。我们通过在量词的后面添加一个?来禁止贪婪。比如：<br>+? 本来是一个或者多个，禁止贪婪后就是一个<br>*? 0个<br>?? 0个<br>{3,5}? 3个<br>{1,} 1个<br>使用,我们看一个例子:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">&lt;body&gt;</span><br><span class="line">   &lt;main&gt;</span><br><span class="line">       &lt;span&gt;houdunwang&lt;<span class="regexp">/span&gt;</span></span><br><span class="line"><span class="regexp">       &lt;span&gt;hdcms.com&lt;/</span>span&gt;</span><br><span class="line">       &lt;span&gt;houdunren.com&lt;<span class="regexp">/span&gt;</span></span><br><span class="line"><span class="regexp">   &lt;/m</span>ain&gt; </span><br><span class="line">&lt;<span class="regexp">/body&gt;</span></span><br><span class="line"><span class="regexp">&lt;script&gt;</span></span><br><span class="line"><span class="regexp">   /</span><span class="regexp">/使用问号禁止贪婪，让量词偏向少的一边</span></span><br><span class="line"><span class="regexp">   </span></span><br><span class="line"><span class="regexp">   /</span><span class="regexp">/例子，将span标签全部替换成h4标签在其前面添上内容"后盾人-"并描红</span></span><br><span class="line"><span class="regexp">   const main = document.querySelector(`main`);</span></span><br><span class="line"><span class="regexp">   /</span><span class="regexp">/若不禁止贪婪的话，因为我们写的是[\s\S]匹配所有字符，同样包括了&lt;/</span>span&gt;</span><br><span class="line">   <span class="comment">//所以最终会匹配成一个这样的内容</span></span><br><span class="line">   <span class="comment">/*  &lt;span&gt;            第一个&lt;span&gt;匹配</span></span><br><span class="line"><span class="comment">             </span></span><br><span class="line"><span class="comment">       houdunwang&lt;/span&gt;</span></span><br><span class="line"><span class="comment">       &lt;span&gt;hdcms.com&lt;/span&gt;</span></span><br><span class="line"><span class="comment">       &lt;span&gt;houdunren.com</span></span><br><span class="line"><span class="comment">                          这一大块[\s\S]+匹配</span></span><br><span class="line"><span class="comment">       &lt;/span&gt;            &lt;\/span&gt;匹配</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="comment">//这样不好。禁止贪婪后便会匹配成一个个独立的span标签</span></span><br><span class="line">   <span class="keyword">let</span> reg = <span class="regexp">/&lt;span&gt;([\s\S]+?)&lt;\/span&gt;/ig</span>;</span><br><span class="line">   main.innerHTML = main.innerHTML.replace(reg,(v,p1) =&gt; &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">`&lt;h4 style="color:red"&gt;后盾人-<span class="subst">$&#123;p1&#125;</span>&lt;/h4&gt;`</span>;</span><br><span class="line">   &#125;);</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<h1 id="全局匹配"><a href="#全局匹配" class="headerlink" title="全局匹配"></a>全局匹配</h1><p>上面已经提到了全局匹配，我们可以使用exec配合g来实现全局匹配，同样match加g也可以。还有一种方法matchAll,下面两个例子体会一下它的用法:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;h1&gt;houdunren.com&lt;<span class="regexp">/h1&gt;</span></span><br><span class="line"><span class="regexp">    &lt;h2&gt;hdcms.com&lt;/</span>h2&gt;</span><br><span class="line">    &lt;h3&gt;后盾人&lt;<span class="regexp">/h3&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="comment">//只取出内容</span></span><br><span class="line">    <span class="keyword">let</span> reg =<span class="regexp">/&lt;(h[1-6])&gt;([\s\S]+?)&lt;\/\1&gt;/ig</span>;</span><br><span class="line">    <span class="keyword">const</span> body = <span class="built_in">document</span>.body;</span><br><span class="line">    <span class="comment">//matchAll函数返回一个迭代器</span></span><br><span class="line">    <span class="keyword">const</span> hd = body.innerHTML.matchAll(reg);</span><br><span class="line">    <span class="comment">//console.log(body.innerHTML.matchAll(reg));</span></span><br><span class="line">    <span class="keyword">let</span> contents = [];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> iterator <span class="keyword">of</span> hd) &#123;</span><br><span class="line">        <span class="comment">//console.dir(iterator);  //打印输出，你看一下控制台的内容，你就知道下面为什么要写iterator[2]</span></span><br><span class="line">        <span class="comment">//因为我们要提取的内容在第二组中</span></span><br><span class="line">        contents.push(iterator[<span class="number">2</span>]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">console</span>.table(contents);</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<p>自定义matchAll方法</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;h1&gt;houdunren.com&lt;<span class="regexp">/h1&gt;</span></span><br><span class="line"><span class="regexp">    &lt;h2&gt;hdcms.com&lt;/</span>h2&gt;</span><br><span class="line">    &lt;h3&gt;后盾人&lt;<span class="regexp">/h3&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="built_in">String</span>.prototype.matchAll = <span class="function"><span class="keyword">function</span>(<span class="params">reg</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">let</span> res = <span class="keyword">this</span>.match(reg);</span><br><span class="line">        <span class="keyword">if</span>(res) &#123;</span><br><span class="line">            <span class="keyword">let</span> str = <span class="keyword">this</span>.replace(res[<span class="number">0</span>], <span class="string">"^"</span>.repeat(res[<span class="number">0</span>].length));</span><br><span class="line">            <span class="keyword">let</span> match = str.matchAll(reg) || [];</span><br><span class="line">            <span class="keyword">return</span> [res,...match];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">let</span> body = <span class="built_in">document</span>.querySelector(<span class="string">"body"</span>).innerHTML;</span><br><span class="line">    <span class="keyword">let</span> search = body.matchAll(<span class="regexp">/&lt;(h[1-6])&gt;([\s\S]+?)&lt;\/\1&gt;/ig</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(search);</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<h1 id="符号的使用"><a href="#符号的使用" class="headerlink" title="$符号的使用"></a>$符号的使用</h1><p>$可以通过$加序号来提取原子组中的内容，我们前面已经知道了，除此之外，它还可以使用($‘)来表示匹配内容右边的内容，用($`)来表示匹配内容左边的内容，用$&amp;表示匹配的所有内容。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;main&gt;</span><br><span class="line">        教育是人人都必须接受的一门艺术，从古至今接受教育的人往往都能巴拉巴拉！</span><br><span class="line">    &lt;<span class="regexp">/main&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="comment">//在字符串前后各再加一个=</span></span><br><span class="line">    <span class="keyword">let</span> hd = <span class="string">'=后盾人='</span>;</span><br><span class="line">    <span class="keyword">let</span> reg = <span class="regexp">/后盾人/</span>;</span><br><span class="line">    <span class="comment">//$`表示匹配内容左边的内容 $'表示匹配内容右边的内容 $&amp;表示匹配的内容</span></span><br><span class="line">    <span class="comment">//第一个是esc下面的那个键  第二个是单引号</span></span><br><span class="line">    <span class="comment">//你这样记，左边的内容就是你左手esc下边的键，右边的内容就是右手的单引号键</span></span><br><span class="line">    <span class="built_in">console</span>.log(hd.replace(reg,<span class="string">"$`$&amp;$'"</span>));</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//$&amp;的使用</span></span><br><span class="line">    <span class="keyword">const</span> main = <span class="built_in">document</span>.querySelector(<span class="string">'body main'</span>);</span><br><span class="line">    main.innerHTML = main.innerHTML.replace(<span class="regexp">/教育/g</span>,<span class="string">`&lt;a href="https://lockme.gitee.io"&gt;$&amp;&lt;/a&gt;`</span>);</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<h1 id="原子组别名"><a href="#原子组别名" class="headerlink" title="原子组别名"></a>原子组别名</h1><p>为了简化原子组的使用方式，有时候我们会为原子组取别名，在组中使用?&lt;别名&gt;来给这个原子组取一个别名，并使用$&lt;别名&gt;引用此原子组，我们看一个例子：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;main&gt;</span><br><span class="line">        &lt;a id=<span class="string">"hd"</span> href=<span class="string">"https://www.houdunren.com"</span>&gt;后盾人&lt;<span class="regexp">/a&gt;</span></span><br><span class="line"><span class="regexp">        &lt;a href="https:/</span><span class="regexp">/www.hdcms.com"&gt;hdcms&lt;/</span>a&gt;</span><br><span class="line">        &lt;a href=<span class="string">"https://www.sina.com.cn"</span>&gt;新浪&lt;<span class="regexp">/a&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/m</span>ain&gt;</span><br><span class="line">&lt;<span class="regexp">/body&gt;</span></span><br><span class="line"><span class="regexp">&lt;script&gt;</span></span><br><span class="line"><span class="regexp">    /</span><span class="regexp">/将上述标签中的内容，转换成[link:'',title:'']这样数组的形式</span></span><br><span class="line"><span class="regexp">    const main = document.querySelector('body main');</span></span><br><span class="line"><span class="regexp">    /</span><span class="regexp">/给组取别名，这样做了之后，iterator中的groups属性，将会生成这样一个对象</span></span><br><span class="line"><span class="regexp">    /</span><span class="regexp">/groups: &#123;link: "https:/</span><span class="regexp">/www.houdunren.com", title: "后盾人"&#125;</span></span><br><span class="line"><span class="regexp">    /</span><span class="regexp">/这样其实就已经到达目的了，用一个容器提取就行了</span></span><br><span class="line"><span class="regexp">    const reg = /</span>&lt;a.*?href=(["'])(?&lt;link&gt;.*?)\1&gt;(?&lt;title&gt;.*?)&lt;\/a&gt;/ig;</span><br><span class="line">    //console.log(main.innerHTML.match(reg));</span><br><span class="line">    const link = [];</span><br><span class="line">    for (const iterator of main.innerHTML.matchAll(reg)) &#123;</span><br><span class="line">           //将对象压入数组中即可</span><br><span class="line">        link.push(iterator["groups"]);</span><br><span class="line">    &#125;</span><br><span class="line">    console.log(link);</span><br><span class="line"></span><br><span class="line">    let hd = `smallbridge`;</span><br><span class="line">    //取别名</span><br><span class="line">    let r = /s(?&lt;con&gt;ma)llbridge/i;</span><br><span class="line">    //取别名后可以使用$&lt;con&gt;取值</span><br><span class="line">    console.log(hd.replace(r,"&lt;h4&gt;$&lt;con&gt;&lt;/h4&gt;"));</span><br><span class="line">    //也可以使用原先的$1取值</span><br><span class="line">    console.log(hd.replace(r,"&lt;h4&gt;$1&lt;/h4&gt;"));</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<h1 id="断言匹配"><a href="#断言匹配" class="headerlink" title="断言匹配"></a>断言匹配</h1><p>断言匹配可以理解成正则表达式自身的条件，用来优化检索的。<br>一共有四种断言，两两匹配，很好记忆，他们分别是：<br>前断言<br>(?&lt;=xxx)  表示匹配前面是xxx的字符<br>(?&lt;!xxx)   表示匹配前面不是xxx的字符<br>后断言<br>(?=xxx)   表示匹配后面是xxx的字符<br>(?!xxx)   表示匹配后面不是xxx的字符<br>注意：前后断言可以一起使用，断言仅仅是用作条件限制，并不会匹配其中的内容用作返回。<br>看几个例子：<br>使用后断言匹配规范价格</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="keyword">let</span> lessons = <span class="string">`</span></span><br><span class="line"><span class="string">     js,200元,300次</span></span><br><span class="line"><span class="string">     php,300.00元,100次</span></span><br><span class="line"><span class="string">     node.js,180元,260次</span></span><br><span class="line"><span class="string">    `</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> reg = <span class="regexp">/(\d+)(.00)?(?=元)/ig</span>;</span><br><span class="line">    lessons = lessons.replace(reg,(v,...args)=&gt;&#123;</span><br><span class="line">        <span class="comment">//console.log(args);</span></span><br><span class="line">        args[<span class="number">1</span>] = args[<span class="number">1</span>] || <span class="string">'.00'</span>;</span><br><span class="line">        <span class="keyword">return</span> args.slice(<span class="number">0</span>,<span class="number">2</span>).join(<span class="string">""</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="built_in">console</span>.log(lessons);</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<p>使用前断言模糊电话号码</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="keyword">let</span> users = <span class="string">`</span></span><br><span class="line"><span class="string">    陈小桥电话: 17398890700</span></span><br><span class="line"><span class="string">    后盾人电话: 13508157296</span></span><br><span class="line"><span class="string">    `</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> reg = <span class="regexp">/(?&lt;=\d&#123;3&#125;)\d&#123;4&#125;(?=\d&#123;4&#125;)/ig</span>;</span><br><span class="line">    users = users.replace(reg,v =&gt;&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">'*'</span>.repeat(<span class="number">4</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="built_in">console</span>.log(users);</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<p>使用断言限制用户关键字</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;main&gt;</span><br><span class="line">        &lt;input type=<span class="string">"text"</span> name=<span class="string">"username"</span>&gt;</span><br><span class="line">    &lt;<span class="regexp">/main&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="keyword">const</span> input = <span class="built_in">document</span>.querySelector(<span class="string">`[name = "username"]`</span>);</span><br><span class="line">    input.addEventListener(<span class="string">"keyup"</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="comment">//不能包含小桥的5到6位字母，字母开头，字母结尾</span></span><br><span class="line">        <span class="keyword">const</span> reg = <span class="regexp">/^(?!.*小桥.*)[a-z]&#123;5,6&#125;$/ig</span>;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="keyword">this</span>.value.match(reg));</span><br><span class="line">    &#125;)</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<p>使用断言排除法统一数据</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;main&gt;</span><br><span class="line">        &lt;a href=<span class="string">"https://www.houdunren.com/1.jpg"</span>&gt;<span class="number">1.</span>jpg&lt;<span class="regexp">/a&gt;</span></span><br><span class="line"><span class="regexp">        &lt;a href="https:/</span><span class="regexp">/oss.houdunren.com/</span><span class="number">2.</span>jpg<span class="string">"&gt;2.jpg&lt;/a&gt;</span></span><br><span class="line"><span class="string">        &lt;a href="</span>https:<span class="comment">//cdn.houdunren.com/3.jpg"&gt;3.jpg&lt;/a&gt;</span></span><br><span class="line">        &lt;a href=<span class="string">"https://houdunren.com/4.jpg"</span>&gt;后盾人&lt;<span class="regexp">/a&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/m</span>ain&gt;</span><br><span class="line">&lt;<span class="regexp">/body&gt;</span></span><br><span class="line"><span class="regexp">&lt;script&gt;</span></span><br><span class="line"><span class="regexp">    const main = document.querySelector("main");</span></span><br><span class="line"><span class="regexp">    const reg = /</span>https:\/\/([a-z]+)?(?&lt;!oss)\..+?(?=\/)/ig;</span><br><span class="line">    <span class="comment">//console.log(main.innerHTML.match(reg));</span></span><br><span class="line">    main.innerHTML = main.innerHTML.replace(reg,()=&gt;&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"https://oss.houdunren.com"</span>;</span><br><span class="line">    &#125;);</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<p>好了，我的分享就到这里了，谢谢大家！</p>

      
      <!-- reward -->
      
      <div id="reward-btn">
        打赏
      </div>
      
    </div>
    
    
      <!-- copyright -->
      
        <div class="declare">
          <ul class="post-copyright">
            <li>
              <i class="ri-copyright-line"></i>
              <strong>版权声明： </strong s>
              本博客所有文章除特别声明外，均采用 <a href="https://www.apache.org/licenses/LICENSE-2.0.html" rel="external nofollow"
                target="_blank">Apache License 2.0</a> 许可协议。转载请注明出处！
            </li>
          </ul>
        </div>
        
    <footer class="article-footer">
      
          
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://lockme.gitee.io/2020/04/12/JS-RegExp-md/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JS%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/" rel="tag">JS正则表达式</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%A4%8D%E4%B9%A0/" rel="tag">复习</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E6%8A%80%E6%9C%AF/" rel="tag">技术</a></li></ul>


    </footer>

  </div>

  
  
  <nav class="article-nav">
    
      <a href="/2020/04/12/JS-Review-four-md/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            JS Review_four.md
          
        </div>
      </a>
    
    
      <a href="/2020/04/12/JS-Review-three-md/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">JS Review_three.md</div>
      </a>
    
  </nav>


  

  
  
<!-- valine评论 -->
<div id="vcomments-box">
    <div id="vcomments">
    </div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='https://cdn.jsdelivr.net/npm/valine@1.3.10/dist/Valine.min.js'></script>
<script>
    new Valine({
        el: '#vcomments',
        app_id: 'pmaQYnbUE9O0H1hiYKLiec4R-gzGzoHsz',
        app_key: 'LMujtI79W4vgEQ3Az5IMo50y',
        path: window.location.pathname,
        notify: 'false',
        verify: 'false',
        avatar: 'mp',
        placeholder: '给我的文章加点评论吧~',
        recordIP: true
    });
    const infoEle = document.querySelector('#vcomments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
        infoEle.childNodes.forEach(function (item) {
            item.parentNode.removeChild(item);
        });
    }
</script>
<style>
    #vcomments-box {
        padding: 5px 30px;
    }

    @media screen and (max-width: 800px) {
        #vcomments-box {
            padding: 5px 0px;
        }
    }

    #vcomments-box #vcomments {
        background-color: #fff;
    }

    .v .vlist .vcard .vh {
        padding-right: 20px;
    }

    .v .vlist .vcard {
        padding-left: 10px;
    }
</style>

  

  
  
  

</article>
</section>
      <footer class="footer">
  <div class="outer">
    <ul class="list-inline">
      <li>
        &copy;
        2020
        月下ctrlc
      </li>
      <li>
        
        Powered by
        
        
        <a href="https://hexo.io" target="_blank">Hexo</a> Theme <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul class="list-inline">
      <li>
        
        
        <span>
  <i>PV:<span id="busuanzi_value_page_pv"></span></i>
  <i>UV:<span id="busuanzi_value_site_uv"></span></i>
</span>
        
      </li>
      
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="to_top">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>
      </div>
    </main>
    <aside class="sidebar">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/avatar.jpg" alt="Small Bridge"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/Vue/">Vue</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="http://shenyu-vip.lofter.com" target="_blank" rel="noopener">主题作者相册</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/2020/03/18/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>拿钱砸死我吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.png">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wechat.png">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/share.js"></script>


<script src="/js/lazyload.min.js"></script>


<script>
  try {
    var typed = new Typed("#subtitle", {
      strings: ['面朝大海，春暖花开', '愿你一生努力，一生被爱', '想要的都拥有，得不到的都释怀'],
      startDelay: 0,
      typeSpeed: 200,
      loop: true,
      backSpeed: 100,
      showCursor: true
    });
  } catch (err) {
  }

</script>




<script src="/js/tocbot.min.js"></script>

<script>
  // Tocbot_v4.7.0  http://tscanlin.github.io/tocbot/
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto',
    onClick: (e) => {
      $('.toc-link').removeClass('is-active-link');
      $(`a[href=${e.target.hash}]`).addClass('is-active-link');
      $(e.target.hash).scrollIntoView();
      return false;
    }
  });
</script>



<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/js/ayer.js"></script>



<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>


<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
      tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
  });

  MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for(i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@2.7.6/unpacked/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
  var ayerConfig = {
    mathjax: true
  }
</script>



<script src="/js/busuanzi-2.3.pure.min.js"></script>



<script type="text/javascript" src="https://js.users.51.la/20544303.js"></script>


    
  </div>
</body>

</html>